package com.xros.demo.gamedataserver.server;

import com.xros.demo.gamedataserver.handler.WorkerInitChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author: mzp
 * @Description: netty服务器
 * @Date: 2024/3/26 14:18
 * @Version: 1.0
 */
@Log4j2
@Component
public class NettyServer implements CommandLineRunner {

    //region （描述：组件）
    /**
     * netty 服务器启动对象
     */
    @Resource
    private ServerBootstrap serverBootstrap;


    /**
     * 负责 worker channel初始化的handler
     */
    @Resource
    private WorkerInitChannelHandler workerInitChannelHandler;


    @Resource
    private NioEventLoopGroup bossGroup;

    @Resource
    private NioEventLoopGroup workerGroup;


    //endregion


    //region （描述：属性）

    /**
     * netty 服务器端口
     */
    private Integer port;

    /**
     * netty 服务器ip
     */
    private String ip;

    //endregion


    @PostConstruct
    private void init() {

        if (port == null) {
            port = 2024;
        }
        if (ip == null) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                ip = "127.0.0.1";
            }
        }
    }


    @Override
    public void run(String... args) {

        try {
            final ChannelFuture bindFuture = serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(workerInitChannelHandler)
                    .bind(port);

            //绑定启动的监听
            bindFuture.addListener((future -> {
                if (future.isSuccess()) {
                    log.info("netty 服务器 \"{}:{}\"启动成功！",ip, port);
                } else {
                    log.error("netty 服务器启动失败");
                }
            }));

            //绑定关闭的监听
            bindFuture.channel().closeFuture().addListener((future -> {
                if (future.isSuccess()) {
                    log.info("netty 服务器 \"{}:{}\"成功关闭！",ip, port);
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                }
            }));


        } catch (Exception e) {
            log.error("启动netty服务器过程中出现异常！异常类型为：{},异常信息为：{}", e.getClass().getName(), e.getMessage());
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
